<template>
    <view class="container">
        <!-- 标题 -->
        <view class="title">智能学习助手</view>

        <!-- 消息展示区域 -->
        <scroll-view class="message-list" :scroll-y="true" :scroll-into-view="scrollIntoView">
           <view
               class="message-item"
               v-for="(item, index) in messages"
               :key="index"
               :class="item.type"
               :id="'msg-' + index"
               @longpress="showMessageOptions(item)"
           >
               <view :class="'message-content ' + item.type">
                   <view class="message-text">{{ item.content }}</view>
               </view>
           </view>
        </scroll-view>

        <!-- 输入框和发送按钮 -->
        <view class="input-container">
            <input class="input" placeholder="请输入您的问题..." @input="handleInput" :value="inputMessage" />
            <button class="send-button" @tap="sendMessage">发送</button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            inputMessage: '',
            messages: [], // 保存对话的消息内容
            scrollIntoView: '' // 控制滚动到底部
        };
    },
    onShow() {
        this.loadMessages(); // 加载本地存储的对话记录
    },
    methods: {
        handleInput(event) {
            this.inputMessage = event.detail.value;
        },
        async sendMessage() {
            const message = this.inputMessage.trim();
            if (!message) {
                return;
            }
            // 用户输入的消息
            this.messages.push({ content: message, type: 'user' });
            this.saveMessages(); // 保存更新后的对话记录

            // 模拟机器人响应
            const reply = await this.getBotReply(message);

            // 机器人回复消息
            this.messages.push({ content: reply, type: 'bot' });
            this.saveMessages(); // 保存更新后的对话记录

            this.inputMessage = '';
            this.scrollIntoView = 'msg-' + (this.messages.length - 1);
        },
        async getBotReply(userMessage) {
            try {
                const response = await uni.request({
                    url: 'https://api.chatanywhere.tech/v1/chat/completions',
                    method: 'POST',
                    data: {
                        model: 'gpt-4o',
                        messages: [
                            {
                                role: 'user',
                                content: userMessage
                            }
                        ]
                    },
                    header: {
                        Authorization: 'Bearer sk-2YlJQv1MYkNbWzrTyjPhDwDyV6yYDdiAVZj2Hvu4wdjrIRIX',
                        'Content-Type': 'application/json'
                    }
                });
                return response[1].data.choices[0].message.content || '抱歉，我没有理解您的问题。';
            } catch (error) {
                console.error(error);
                return '请求失败，请稍后重试。';
            }
        },
        showMessageOptions(message) {
            if (message.type === 'bot') {
                // 仅对机器人的消息提供“复制”和“收藏”功能
                uni.showActionSheet({
                    itemList: ['复制', '收藏'],
                    success: (res) => {
                        if (res.tapIndex === 0) {
                            // 复制功能
                            uni.setClipboardData({
                                data: message.content,
                                success: () => {
                                    uni.showToast({ title: '已复制', icon: 'success' });
                                }
                            });
                        } else if (res.tapIndex === 1) {
                            // 收藏功能，跳转到收藏页面
                            uni.navigateTo({
                                url: `/pages/collect/collect?content=${encodeURIComponent(message.content)}`
                            });
                        }
                    },
                    fail: (err) => {
                        console.error(err);
                    }
                });
            }
        },
        saveMessages() {
            // 保存消息到本地存储
            uni.setStorageSync('chatMessages', this.messages);
        },
        loadMessages() {
            // 从本地存储加载消息
            const savedMessages = uni.getStorageSync('chatMessages') || [];
            this.messages = savedMessages;
            if (this.messages.length > 0) {
                this.scrollIntoView = 'msg-' + (this.messages.length - 1); // 滚动到最后一条消息
            }
        }
    }
};
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    padding: 20rpx;
    background-color: #f7f8fa;
}

/* 标题样式 */
.title {
    font-size: 36rpx;
    font-weight: bold;
    color: #7e57c2;
    text-align: center;
    margin-top: 30rpx;
    margin-bottom: 20rpx;
}

/* 消息展示区域 */
.message-list {
    flex: 1;
    padding: 20rpx;
    margin-bottom: 20rpx;
    overflow-y: scroll;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}

/* 消息单项样式 */
.message-item {
    display: flex;
    margin-bottom: 16rpx;
}
.message-item.user {
    justify-content: flex-end; /* 让用户消息显示在右侧 */
}
.message-item.bot {
    justify-content: flex-start; /* 让机器人消息显示在左侧 */
}
.message-content {
    padding: 20rpx;
        border-radius: 16rpx;
        max-width: 70%;
        word-wrap: break-word;
        font-size: 28rpx;
        line-height: 1.6;
        box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.1);
}
.message-content.user {
    background-color: #7e57c2;
    color: #fff;
    align-self: flex-end;
}
.message-content.bot {
    background-color: #ececec;
    color: #333;
    align-self: flex-start;
}

/* 输入框容器 */
.input-container {
    display: flex;
    align-items: center;
    padding: 10rpx 20rpx;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}

/* 输入框样式 */
.input {
    flex: 1;
    height: 80rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    border: 1px solid #ccc;
    border-radius: 16rpx;
    margin-right: 20rpx;
    box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.1);
}

/* 发送按钮样式 */
.send-button {
    height: 80rpx;
    padding: 0 30rpx;
    background-color: #7e57c2;
    color: #fff;
    font-size: 28rpx;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.2);
    cursor: pointer;
    transition: background-color 0.3s ease;
}
.send-button:hover {
    background-color: #673ab7;
}
</style>
